$(() => {
    const $container = $('body > .container');
    const tempId = Date.now();
    const save = data => {
        return new Promise((resolve, reject) => {
            //获取表单
            const { form } = data;
            const formData = getFormData(form);
            if (!formData) {
                reject();
            }
            // 字符串转数组
            if (formData.examMethods && typeof formData.examMethods === 'string') {
                formData.examMethods = formData.examMethods.split(',').map(e => { return { oid: e } });
            }
            if (formData.patientFeatures && typeof formData.patientFeatures === 'string') {
                formData.patientFeatures = formData.patientFeatures.split(',').map(e => { return { oid: e } })
            }
            formData.patient.namePinYin = formData.namePinYin;
            formData.patient.birthDate = formData.birthDate;
            //调用接口
            ris.ajax(`/api/register/save`, { data: { examDto: formData, editReason: formData.editReason }, type: 'POST' })
                .then((result) => {
                    document.title = `${formData.patient?.name ?? formData.accessionNumber} | 登记`;
                    resolve(result);
                })
                .catch(reject);
        });
    };
    const submit = data => {
        return new Promise((resolve, reason) => {
            save(data).then(result => {
                const examId = result.data;
                //验证
                ris.validateExam(examId, 'Register').then(() => {
                    //调用接口
                    ris.ajax(`/api/register/submit`, { data: { examId }, type: 'POST' }).then(() => {
                        resolve();
                    });
                });
            });
        });
    };
    //新建
    $container.on('new', (_, data) => {
        ris.ajax(`/api/register/create/${data.data.id}`).then(result => {
            if (result.success) {
                window.open(`/register/detail?oid=${encodeURIComponent(result.data)}`, '_blank');
            }
        });
    });
    //打开
    $container.on('open', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(result => {
            if (result.length === 0) {
                DevExpress.ui.notify('请选择需要打开的检查', 'error');
            } else {
                window.open(`/register/detail?oid=${encodeURIComponent(result[0])}`, '_blank');
            }
        });
    });
    //保存
    $container.on('save', (_, data) => {
        //调用接口
        save(data).then(() => {
            DevExpress.ui.notify('保存成功', 'success');
        });
    });
    //编辑
    $container.on('edit', (_, data) => {
        //form表单可以编辑
        openEditPopup('修正原因', '修正').then(result => {
            const { form, updateToolbarItems } = data;
            const formData = getFormData(form);
            if (!formData) return false;
            formData.isDisabled = false;
            formData.editReason = result.reason;
            form.setData(formData);
            if (updateToolbarItems && updateToolbarItems instanceof Function) {
                updateToolbarItems(formData, true);
            }
        });
    });
    //提交
    $container.on('submit', async (_, data) => {
        submit(data).then(() => {
            DevExpress.ui.notify('提交成功', 'success');
            refreshForm(data);
        });
    });
    //删除
    $container.on('delete', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要删除的检查', 'error');
            } else {
                //调用删除接口
                $.invokeAction(
                    '删除',
                    `/api/register/delete`,
                    { examIds: oids },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('删除成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    //刷新
    $container.on('refresh', (_, data) => {
        refreshDataGrid(data);
    });
    // 自动刷新
    $container.on('autoRefresh', (_, data) => {
        const { component, key, intervalKey } = data.data;
        component.itemData.text = autoRefresh(key, intervalKey, () => {
            //获取表格
            refreshDataGrid(data);
        });
        component.component.repaint();
    });
    // 刷新间隔时间
    $container.on('refreshInterval', (_, data) => {
        const { key, intervalKey } = data.data;
        refreshInterval(key, intervalKey, () => {
            //获取表格
            refreshDataGrid(data);
        });
    });
    //撤回预约
    $container.on('revoke', async (_, data) => {
        await verifyArchive(data);
        getOid(data).then(oid => {
            //调用取消接口
            //调用invokeAction
            $.invokeAction(
                '撤回预约',
                `/api/register/revoke`,
                { examId: oid },
                { actionUrl: '/api/workflow/invoke' }
            ).then(result => {
                if (result.success) {
                    DevExpress.ui.notify('撤回成功', 'success');
                    refreshForm(data);
                }
            });
        });
    });
    //退费
    $container.on('refund', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要退费的检查', 'error');
            } else {
                //调用退费接口
                //调用invokeAction
                $.invokeAction(
                    '退费',
                    `/api/register/refund`,
                    { examIds: oids },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('退费成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    //查看报告
    $container.on('viewReport', (_, data) => {
        getOids(data, (rowsData) => {
            let reportUrls = rowsData.filter(e => e.isArchive).map(e => e.reportUrl);
            if (reportUrls && reportUrls.length === 0) return true;
            if (reportUrls && reportUrls.length >= 0) {
                reportUrls.forEach(e => {
                    ris.viewReport(e);
                })
            }
            if (rowsData.filter(e => !e.isArchive).length > 0) {
                return true;
            }
        }).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要查看报告的检查', 'error');
            } else {
                ris.ajax(`/api/report/get-report-pdf-files`, { type: 'POST', data: { examIds: oids }, errorMessage: '打印服务启动失败' }).then(result => {
                    if (result.success) {
                        if (result.error) {
                            DevExpress.ui.notify(result.error, 'error');
                        }
                        result.data.forEach(e => {
                            ris.viewReport(e);
                        })
                    } else {
                        DevExpress.ui.notify(result.error, 'error');
                    }
                })
            }
        }).catch(e => { return; });
    });
    //查看图像
    $container.on('viewImage', (_, data) => {
        getOids(data, (rowsData) => {
            let reportImagesPaths = rowsData.filter(e => e.isArchive).map(e => e.reportImagesPath);
            if (reportImagesPaths && reportImagesPaths.length === 0) return true;
            if (reportImagesPaths && reportImagesPaths.length >= 0) {
                reportImagesPaths.forEach(e => {
                    ris.viewImage(e);
                })
            }
            if (rowsData.filter(e => !e.isArchive).length > 0) {
                return true;
            }
        }).then(ids => {
            if (ids.length === 0) {
                DevExpress.ui.notify('请选择需要查看图像的检查', 'error');
            } else {
                ris.ajax('/api/exam/get-dicom-client-url').then(result => {
                    if (result.success && result.data) {
                        let url = result.data;
                        if (result.data.includes('?')) {
                            url += `&examIds=${ids.join(',')}`;
                        } else {
                            url += `?examIds=${ids.join(',')}`;
                        }
                        ris.viewImage(url);
                    } else {
                        DevExpress.ui.notify(result.error, 'error');
                    }
                });
            }
        })
    });
    printFormPdf = async (examId, style) => {
        const pdfUrl = `/api/exam/get-form-pdf-file?examId=${examId}&style=${style.id}`;
        if (ris.host) {
            await ris.host.printPdf(pdfUrl, style.text);
        } else {
            window.open(pdfUrl, '_blank');
        }
    };

    //打印
    $container.on('print', (_, data) => {
        //获取打印的文件类型
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要打印的检查', 'error');
            } else {
                const print = () => {
                    //调用打印接口
                    if (data.data.id === 'Report') {
                        ris.ajax(`/api/report/get-report-pdf-files`, { type: 'POST', data: { examIds: oids }, errorMessage: '打印服务启动失败' }).then(result => {
                            if (result.success) {
                                setTimeout(async () => {
                                    for (var url of result.data) {
                                        await ris.printReport(url);
                                    }
                                });
                            } else {
                                DevExpress.ui.notify(result.error, 'error');
                            }
                        })
                    } else {
                        setTimeout(async () => {
                            for (const oid of oids) {
                                await printFormPdf(oid, data.data);
                            }
                        });
                    }
                };
                if (data.form && ris.verify('登记_打印并提交')) {
                    if (data.form.getData()?.examStatus === 0) {
                        submit(data).then(() => {
                            print();
                        });
                    } else {
                        print();
                    }
                } else {
                    print();
                }
            }
        });
    });
    //扫描单据
    $container.on('scan', (_, data) => {
        ris.ajax('http://localhost:5003/scan', { errorMessage: '扫描程序启动失败' }).then(result => {
            if (result.success) {
                // form表单设置值
                const { form } = data;
                // 调用form函数
                form.setValue('', '');
                DevExpress.ui.notify('打印成功', 'success');
            } else {
                DevExpress.ui.notify(result.error, 'error');
            }
        })
    });
    //刷卡
    $container.on('swipe', (_, data) => {
        //调用刷卡接口
        const { swipeType } = data.data;
        let dataSource = localStorage.getItem('selected-dataSource');
        if (!dataSource) {
            DevExpress.ui.notify('请选择数据来源', 'error');
            return false;
        }
        ris.ajax(`http://localhost:5003/swipe?type=${swipeType}&dataSource=${dataSource}`, { errorMessage: '程序启动失败' }).then(result => {
            let data = JSON.parse(result);
            data.success = true;
            if (data.success) {
                // 打开弹窗
                // 把获得的卡号传过去
                data.Number = '111111';
                $eventEmitter.trigger('search', {
                    data: {
                        text: data.number
                    }
                })
            } else {
                DevExpress.ui.notify(data.error, 'error');
            }
        });
    });
    //查询
    $container.on('search', (_, data) => {
        let dataSource = localStorage.getItem('selected-dataSource');
        if (!dataSource) {
            DevExpress.ui.notify('请选择数据来源', 'error');
            return false;
        }
        const { text } = data.data ?? {};
        openSwipPopup(text, dataSource, async examItemNumbers => {
            const result = await ris.ajax(`/api/exam-apply/add-exam/${dataSource}`, {
                type: 'POST',
                data: JSON.stringify(examItemNumbers),
                contentType: 'application/json;charset=UTF-8',
                headers: {
                    "tempId": tempId
                },
            });
            if (result.success) {
                setTimeout(() => {
                    window.open(`/register/detail?oid=${encodeURIComponent(result.data)}`, '_blank');
                });
                return true;
            } else {
                DevExpress.ui.notify(result.error, 'error');
            }
        });
    });
    //合并
    $container.on('merge', (_, data) => {
        //需要选择数据
        //合并完了，需要回调HIS接口，返回状态//是否需要放在工作流中？
        let dataSource = localStorage.getItem('selected-dataSource');
        if (!dataSource) {
            DevExpress.ui.notify('未找到数据来源', 'error');
            return false;
        }
        const { examGrid } = data;
        let examItemNumbers = (examGrid && examGrid.getSelectedRowKeys());
        if (examItemNumbers.length === 0) {
            DevExpress.ui.notify('请选择检查项目', 'error');
        } else {

        }
    });
    // 到诊
    $container.on('arrival', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要到诊的检查', 'error');
            } else {
                $.invokeAction(
                    '到诊',
                    `/api/register/arrived`,
                    { examIds: oids },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('到诊成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    // 置顶
    $container.on('top', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要置顶的检查', 'error');
            } else {
                $.invokeAction(
                    '置顶',
                    `/api/register/top`,
                    { examId: oids[0] },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('置顶成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    // 置前
    $container.on('previous', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要置前的检查', 'error');
            } else {
                $.invokeAction(
                    '置前',
                    `/api/register/pre`,
                    { examId: oids[0] },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('置前成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    // 置后
    $container.on('next', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要置后的检查', 'error');
            } else {
                $.invokeAction(
                    '置后',
                    `/api/register/next`,
                    { examId: oids[0] },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('置后成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    // 置底
    $container.on('bottom', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要置底的检查', 'error');
            } else {
                $.invokeAction(
                    '置底',
                    `/api/register/bottom`,
                    { examId: oids[0] },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('置底成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    // 插入
    $container.on('insert', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要操作的检查', 'error');
            } else {
                $.invokeAction(
                    '插入',
                    `/api/register/insert`,
                    { examId: oids[0] },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('插入成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    // 挂起
    $container.on('suspend', async (_, data) => {
        await verifyArchive(data);
        //获取表格
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要挂起的检查', 'error');
            } else {
                //调用取消接口
                //调用invokeAction
                $.invokeAction(
                    '挂起',
                    `/api/register/pending`,
                    { examIds: oids },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('挂起成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    // 取消挂起
    $container.on('cancelSuspend', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要取消挂起的检查', 'error');
            } else {
                $.invokeAction(
                    '取消挂起',
                    `/api/register/cancel-pending`,
                    { examIds: oids },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('取消成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    // 绿色通道
    $container.on('greenChannel', (_, data) => {
        $.invokeAction(
            '绿色通道',
            `/api/register/emergency-register`,
            null,
            { actionUrl: '/api/workflow/invoke' }
        ).then(result => {
            if (result.success) {
                refreshDataGrid(data);
            }
        });
    });
    // 全选
    $container.on('selectAll', (_, data) => {
        const { examGrid } = data;
        if (examGrid) {
            examGrid.selectAll();
        }
    });
    // 反选
    $container.on('invertSelect', (_, data) => {
        const { examGrid } = data;
        if (examGrid) {
            examGrid.invertSelect();
        }
    });
    $container.on('dataSourceValueChanged', (_, data) => {
        const { value } = data.data;
        if (value) {
            if (localStorage.getItem('selected-dataSource')) {
                localStorage.removeItem('selected-dataSource')
            }
            localStorage.setItem('selected-dataSource', value);
        }
    });
    $container.on('study', (_, data) => {
        //打开弹窗
        openStudyPopup();
    });
    $container.on('consultation', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要申请会诊的检查', 'error');
            } else {
                ris.ajax(`/api/study/create-study-exam`, { type: 'POST', data: { studyIds: oids } }).then(result => {
                    if (result.success) {
                        window.open(`/register/detail?oid=${encodeURIComponent(result.data)}`, '_blank');
                    }
                })
            }
        });
    });
    $container.on('studySearch', (_, data) => {
        const { examGrid } = data
        if (examGrid) {
            const { text } = data.data;
            examGrid.refresh({
                userData: {
                    number: text
                }
            })
        }
    });
    $container.on('today', (_, data) => {
        const { examGrid } = data
        if (examGrid) {
            examGrid.refresh({
                userData: {
                    date: 'today'
                }
            })
        }
    });
    $container.on('yesterday', (_, data) => {
        const { examGrid } = data
        if (examGrid) {
            examGrid.refresh({
                userData: {
                    date: 'yesterday'
                }
            })
        }
    });
    $container.on('lastThreeDays', (_, data) => {
        const { examGrid } = data
        if (examGrid) {
            examGrid.refresh({
                userData: {
                    date: 'lastThreeDays'
                }
            })
        }
    });
    $container.on('applyConsultation', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要申请会诊的检查', 'error');
            } else {
                //调用删除接口
                $.invokeAction(
                    '申请会诊',
                    `/api/study/apply-consultation`,
                    { examIds: oids },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        DevExpress.ui.notify('申请成功', 'success');
                        refreshDataGrid(data);
                    }
                });
            }
        });
    });
    $container.on('supplementarySync', async (_, data) => {
        await verifyArchive(data);
        let dataSource = localStorage.getItem('selected-dataSource');
        if (!dataSource) {
            DevExpress.ui.notify('请选择数据来源', 'error');
            return false;
        }
        getOids(data).then(oids => {
            if (oids.length != 1) {
                DevExpress.ui.notify('请选择一条数据进行补录', 'error');
            }
            else {
                $.invokeAction(
                    '补录验证',
                    `/api/exam-apply/get-supplementary-view`,
                    { examId: oids[0] },
                    { actionUrl: '/api/workflow/invoke' }
                ).then(result => {
                    if (result.success) {
                        openSwipPopup('', dataSource, async examItemNumbers => {
                            const result = await ris.ajax(`/api/exam-apply/supplementary-exam/${dataSource}`, {
                                type: 'POST',
                                data: { examItemNumbers, examId: oids[0] },
                                headers: {
                                    "tempId": tempId
                                },
                            });
                            if (result.success) {
                                setTimeout(() => {
                                    DevExpress.ui.notify('同步补录成功', 'success');
                                    refreshDataGrid(data);
                                });
                                return true;
                            } else {
                                DevExpress.ui.notify(result.error, 'error');
                            }
                        });
                    }
                });
            }
        })
    });
    $container.on('examEvent', async (_, data) => {
        await verifyArchive(data);
        getOids(data).then(oids => {
            if (oids.length === 0) {
                DevExpress.ui.notify('请选择需要查看检查事件的检查', 'error');
            } else if (oids.length !== 1) {
                DevExpress.ui.notify('请选择一个需要查看检查事件数据的检查', 'error');
            } else {
                openExamEventPopup(oids[0])
            }
        });
    });
    $container.on('export', (_, data) => {
        const { params } = data;
        if (params) {
            const { exportData } = params;
            if (exportData instanceof Function) {
                exportData((loadOptions) => {
                    const exportList = () => {
                        ris.ajax('/api/register/export', { data: loadOptions, type: 'POST', contentType: 'application/json;charset=UTF-8', dataType: 'json' }).then(result => {
                            if (result.data) {
                                window.open(`/api/export-list/${result.data}?fileName=检查表`, '_blank');
                            }
                        });
                    };
                    if (data.examGrid.totalCount() > 1000) {
                        DevExpress.ui.dialog.confirm("导出数据过多，是否继续导出？", "导出列表").done(result => {
                            if (result) {
                                exportList();
                            }
                        })
                    } else {
                        exportList();
                    }
                })
            }
        }
    });
    const verifyArchive = (data) => {
        return new Promise((resolve, reject) => {
            // 获取多选数据
            const { examGrid } = data;
            let rowsData = (examGrid && examGrid.getSelectedRowsData());
            if (rowsData && rowsData.length > 0) {
                var isArchive = rowsData.filter(e => e.isArchive);
                if (isArchive.length > 0) {
                    DevExpress.ui.notify('存在已归档的数据', 'error');
                    reject();
                }
            }
            resolve();
        })
    }
    // 获取Oids
    const getOids = (data,func) => {
        return new Promise((resolve, reject) => {
            // 获取多选数据
            const { examGrid } = data;
            let rowsData = (examGrid && examGrid.getSelectedRowsData());
            if (func && func instanceof Function && rowsData) {
                let reuslt = func(rowsData);
                if (!reuslt) {
                    reject();
                }
            }
            let oids = rowsData ? rowsData.filter(e => !e.isArchive).map(e => e.oid) : [];
            if ((!oids) || oids.length === 0) {
                // 获取行数据||form
                getOid(data).then(result => {
                    resolve(result ? [result] : []);
                })
            } else {
                resolve(oids ? oids : []);
            }
        })
    }
    // 获取Oid
    const getOid = (data) => {
        return new Promise((resolve, reject) => {
            let oid = undefined;
            //key
            if (data.data) {
                oid = data.data.oid;
            }
            if (!oid) {
                //获取表格||form中的Oid
                const { form } = data;
                let formData = getFormData(form);
                if (formData) {
                    oid = formData.oid;
                }
            }
            resolve(oid);
        });
    };
    // 获取form数据
    const getFormData = (form) => {
        return !form ? console.error('未获取到form对象') : $.isEmptyObject(form.getData()) ? console.error('form对象为空对象') : form.getData();
    }
    // 开发刷卡弹窗
    const openSwipPopup = (number, dataSource, addExamItems) => {
        let dataGrid;
        const popup = $(`<div>`)
            .appendTo('body')
            .dxPopup({
                width: '85%',
                height: '90%',
                container: 'body',
                showTitle: true,
                title: `查询结果`,
                visible: true,
                dragEnabled: false,
                position: {
                    at: 'center',
                    my: 'center',
                    collision: 'fit',
                },
                toolbarItems: [
                    {
                        location: 'after',
                        toolbar: 'bottom',
                        widget: 'dxButton',
                        options: {
                            text: '确定',
                            onClick: async () => {
                                let examItemNumbers = (dataGrid && dataGrid.getSelectedRowKeys());
                                if (examItemNumbers.length === 0) {
                                    DevExpress.ui.notify('请选择检查项目', 'error');
                                } else {
                                    if (await addExamItems(examItemNumbers)) {
                                        popup.hide();
                                    }
                                }
                            },
                        },
                    },
                    {
                        location: 'after',
                        toolbar: 'bottom',
                        widget: 'dxButton',
                        options: {
                            text: '取消',
                            onClick: () => {
                                popup.hide();
                            },
                        },
                    },
                ],
                contentTemplate: container => {
                    const $contentDiv = $(`<div class='p-c'>`).appendTo(container);
                    //高级搜索
                    const advancedSearch = $('<div>').appendTo($contentDiv).advancedSearchWithCollapse(null, e => {
                        dataGrid.refresh({ userData: e });
                    });
                    //number ? advancedSearch.collapse() : advancedSearch.expand();
                    $.get('/api/exam-apply/get-advanced-search-view').then(result => {
                        if (result.success) {
                            if (result.view) {
                                advancedSearch.updateView(result.view, result.data);
                            }
                        }
                    });
                    //表格
                    dataGrid = $('<div class="p-datagrid"></div>')
                        .appendTo($contentDiv)
                        .dataGrid({
                            id: 'register-exam-item-grid',
                            key: 'examItemNumber',
                            remoteOperations: false,
                            onLoad(loadOptions) {
                                //根据data返回的数据查询检查列表
                                return new Promise((resolve, reject) => {
                                    $.post({
                                        url: `/api/exam-apply/get-interface-service-list-${dataSource}?number=${number}`,
                                        dataType: 'json',
                                        contentType: 'application/json;charset=UTF-8',
                                        data: JSON.stringify(loadOptions),
                                        headers: {
                                            "tempId": tempId
                                        },
                                        success: result => {
                                            if (result.success) {
                                                setTimeout(() => {
                                                    dataGrid.unselectAll();
                                                    if (number && $.isEmptyObject(loadOptions.userData)) {
                                                        dataGrid.selectAll();
                                                    }
                                                }, 200);
                                                resolve(result)
                                            } else {
                                                reject(result.error);
                                            }
                                        }
                                    });
                                })
                            },
                            toolbar: {
                                items: [
                                    {
                                        location: 'after',
                                        widget: 'dxButton',
                                        options: {
                                            name: 'selectAll',
                                            text: '选择全部',
                                            onClick: () => {
                                                dataGrid.selectAll();
                                            }
                                        }
                                    }, {
                                        location: 'after',
                                        widget: 'dxButton',
                                        options: {
                                            name: 'invertSelect',
                                            text: '反向选择',
                                            onClick: () => {
                                                dataGrid.invertSelect();
                                            }
                                        },
                                    }
                                ]
                            }
                        });
                },
                onHidden(e) {
                    //关闭时销毁
                    e.component.dispose();
                    $(e.element).remove();
                },
            })
            .dxPopup('instance');
    };
    // 刷新form
    const refreshForm = (data) => {
        getOid(data).then(oid => {
            return ris.ajax(`/api/register/${oid}/get-exam`)
        }).then(result => {
            const { form } = data;
            result.data.isDisabled = result.data.examStatus !== 0;
            let formData = result.data;
            if (formData.examMethods && formData.examMethods instanceof Array) {
                formData.examMethods = formData.examMethods.map(e => e.oid).join(',');
            }
            if (formData.patientFeatures && formData.patientFeatures instanceof Array) {
                formData.patientFeatures = formData.patientFeatures.map(e => e.oid).join(',');
            }
            form.setData(formData);
            const { updateToolbarItems } = data;
            if (updateToolbarItems && updateToolbarItems instanceof Function) {
                updateToolbarItems(result.data);
            }
        })
    }
    // 打开远程会诊
    const openStudyPopup = () => {
        $('<div>')
            .appendTo('body')
            .dxPopup({
                width: '85%',
                height: '90%',
                container: 'body',
                showTitle: true,
                title: `远程会诊`,
                visible: true,
                dragEnabled: false,
                position: {
                    at: 'center',
                    my: 'center',
                    collision: 'fit',
                },
                contentTemplate: container => {
                    const $contentDiv = $('<div class="p-c"></div>').appendTo(container);
                    //工具栏
                    const toolbar = $('<div>').appendTo($contentDiv).dxToolbar({ elementAttr: { style: 'border-bottom: 2px solid #eee' } }).dxToolbar('instance');
                    //表格
                    const dataGrid = $('<div class="p-datagrid"></div>')
                        .appendTo($contentDiv)
                        .dataGrid({
                            paging: { pageIndex: 0, pageSize: 50 },
                            onLoad(loadOptions) {
                                return new Promise((resolve, reject) => {
                                    $.post({
                                        url: `/api/study/get-list`,
                                        dataType: 'json',
                                        contentType: 'application/json;charset=UTF-8',
                                        data: JSON.stringify(loadOptions),
                                        success: result => {
                                            if (result.success) {
                                                result.data.columns = [{
                                                    dataField: "oid",
                                                    visible: false
                                                }, {
                                                    dataField: "studyKey",
                                                    visible: false
                                                }, {
                                                    dataField: "apply",
                                                    caption: "申请状态",
                                                    width: 150
                                                }, {
                                                    dataField: "accessionNumber",
                                                    caption: "检查号",
                                                    width: 150
                                                }, {
                                                    dataField: "patientName",
                                                    caption: "姓名",
                                                    width: 150
                                                }, {
                                                    dataField: "patientSex",
                                                    caption: "性别",
                                                    width: 80
                                                }, {
                                                    dataField: "patientAge",
                                                    caption: "年龄",
                                                    width: 80
                                                }, {
                                                    dataField: "patientId",
                                                    caption: "患者Id",
                                                    width: 150
                                                }, {
                                                    dataField: "studyId",
                                                    caption: "检查Id",
                                                    width: 150
                                                }, {
                                                    dataField: "deviceName",
                                                    caption: "设备",
                                                    width: 80
                                                }, {
                                                    dataField: "studyDateTime",
                                                    caption: "检查日期",
                                                    dataType: "datetime",
                                                    width: 150
                                                }, {
                                                    dataField: "manufacturer",
                                                    caption: "制造商"
                                                }, {
                                                    dataField: "manufacturerModelName",
                                                    caption: "制造商型号"
                                                }]
                                                resolve(result)
                                            } else {
                                                reject(result.error);
                                            }
                                        }
                                    });
                                })
                            },
                            onCellPrepared(e) {
                                if (e.rowType === 'data' && e.data && e.column.dataField === 'apply') {
                                    if (e.data.apply) {
                                        const $apply = $('<span class="badge rounded-pill" />')
                                            .css('cssText', `font-size:12px;font-weight:normal;background-color: #95a5a6ca !important`)
                                            .text('已申请');
                                        e.cellElement.empty().append($apply);
                                    } else {
                                        const $apply = $('<span class="badge rounded-pill" />')
                                            .css('cssText', `font-size:12px;font-weight:normal;background-color: #c0392bca !important`)
                                            .text('未申请');
                                        e.cellElement.empty().append($apply);
                                    }
                                }
                            }
                        });
                    const tools = $.getRegisterTools($container, null, null, dataGrid);
                    //设置工具栏
                    toolbar.option('items', [
                        tools.studySearch,
                        tools.consultation,
                        tools.today,
                        tools.yesterday,
                        tools.lastThreeDays,
                    ]);
                },
                onHidden(e) {
                    //关闭时销毁
                    e.component.dispose();
                    $(e.element).remove();
                },
            })
            .dxPopup('instance');
    }
    // 刷新表格
    const refreshDataGrid = (data) => {
        //获取表格
        const { params } = data;
        if (params) {
            const { reloadGrid } = params;
            if (reloadGrid instanceof Function) {
                reloadGrid();
            }
        } else {
            const { examGrid } = data;
            examGrid.refresh();
        }
    }
    // 打开编辑弹窗
    const openEditPopup = (label, title) => {
        return $('<div />').dxForm({
            labelLocation: 'left',
            // labelMode: "static",
            items: [{
                dataField: 'reason',
                editorType: 'dxTextArea',
                label: { text: label },
                editorOptions: {
                    height: 90,
                    maxLength: 200,
                }
            }],
        }).formPopup({
            title: title,
            maxWidth: 600,
            maxHeight: 350,
        })
    }

    const openExamEventPopup = (examId) => {
        const popup = $('<div>')
            .appendTo('body')
            .dxPopup({
                width: '40%',
                height: '40%',
                minWidth: '700px',
                minHeight: '500px',
                container: 'body',
                showTitle: true,
                title: `检查事件`,
                visible: true,
                dragEnabled: false,
                position: {
                    at: 'center',
                    my: 'center',
                    collision: 'fit',
                },
                toolbarItems: [{
                    location: 'after',
                    toolbar: 'bottom',
                    widget: 'dxButton',
                    options: {
                        text: '关闭',
                        onClick: () => {
                            popup.hide();
                        },
                    },
                }],
                contentTemplate: container => {
                    const $contentDiv = $('<div class="p-c"></div>').appendTo(container);
                    //表格
                    $('<div class="p-datagrid"></div>')
                        .appendTo($contentDiv)
                        .dataGrid({
                            paging: { enabled: false },
                            pager: { visible: false },
                            remoteOperations: false,
                            onLoad(loadOptions) {
                                return new Promise((resolve, reject) => {
                                    $.get({
                                        url: `/api/exam-event/get-exam-events?examId=${examId}`,
                                        success: result => {
                                            if (result.success) {
                                                resolve(result)
                                            } else {
                                                reject(result.error);
                                            }
                                        }
                                    });
                                })
                            }
                        });
                },
                onHidden(e) {
                    //关闭时销毁
                    e.component.dispose();
                    $(e.element).remove();
                },
            })
            .dxPopup('instance');
    }
});
